import { defineStore } from 'pinia';
// @ts-ignore
import { getUserInfo } from '@/plugins/api/user';
import { login } from '@/plugins/api/public';
import { setStorageSync, setToken, setUserInfo } from '../../storage';
import { store } from '@/store/pinia'


export interface UserState {
    userId: string,
    token: string,
    userInfo: object
}

const userState: UserState = {
    userId: '',
    token: '',
    userInfo: {}
}

export const userStore = defineStore('user', {
    state: () => userState,
    actions: {
        async login(userInfo: object | any): Promise<any> {
            const { username, password } = userInfo
            // @ts-ignore
            const {data} = await login({account:username, password})
            if (data) {
                const { token } = data
                if (token) {
                    this.$state.token = token;
                    setToken(token);
                    await this.getUserInfo();
                }
                else {
                    return Promise.reject('未正常返回token')
                }
            }
        },
        async getUserInfo(): Promise<any> {
            const res = await getUserInfo();
            console.log(res)
            if (res.code === 200) {
                this.$state.userInfo = res.data;
                setUserInfo(res.data);
                if (res.data.theme) {
                    setStorageSync('theme', res.data.theme)
                }
            }
        }
    },
    getters: {
        gettersUserId: (state) => state.userId,
        gettersToken: (state) => state.token,
        gettersUserInfo: (state) => state.userInfo
    }
})

export const useUser = () => userStore(store);